<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>移动div</title>
	<style type="text/css">
	*{padding:0px;margin:0px;}
	#move{width:150px;height:150px;background:lightblue;border-radius:20%;position:absolute;}


	</style>
</head>
<body>
	<div id='move'></div>


	<script type="text/javascript">
	//获取元素
	var move = document.getElementById('move');
	var step = 5;

	window.onkeydown = function(e)
	{
		var res = e.keyCode;
		console.log(res);

		switch(res) {
			case 39:
			case 68:
				moveRight();
			break;
			case 37:
			case 65:
				moveLeft();
			break;
			case 38:
			case 87:
				moveTop();
			break;
			case 40:
			case 83:
				moveDown();
			break;
		}



		//向右移动
		function moveRight()
		{
			//获取当前元素的左偏移量
			var r = move.offsetLeft;
			var nr = r + step;
			move.style.left = nr +'px';
		}

		//向左移动
		function moveLeft()
		{
			//获取当前元素的左偏移量
			var l = move.offsetLeft;
			var nl = l - step;
			move.style.left = nl+'px';
		}
		//向上移动
		function moveTop()
		{
			//获取当前元素的顶部偏移量
			var t = move.offsetTop;
			var nt = t - step;
			move.style.top = nt+'px';
		}

		//向下移动
		function moveDown()
		{
			//
			var d = move.offsetTop;
			var nd = d + step;
			move.style.top = nd+'px';
		}

	}



	</script>
</body>
</html>